const {appId, masterKey, serverURL} = require('../../config').parse
const names = ['objectId', 'ACL']

async function clearData (name, model) {
  const q = new Parse.Query(name)
  if (model) {
    q.equalTo('name', model)
  }
  const list = await q.limit(1000).find({useMasterKey: true})
  await Parse.Object.destroyAll(list, {useMasterKey: true})
}

const clearAll = async () => {
  const names = ['SyResource', 'SyGrid', 'SyEditor', 'SyQuery']

  for (let i = 0; i < names.length; i++) {
    console.log(`clear${names[i]}`)
    await clearData(names[i])
  }
  console.log('done')
}

Parse.Cloud.define('clearSchema', async function (req, res) {
  const {model} = req.params
  console.log(`clear ${model}`)

  try {
    const names = ['SyResource', 'SyGrid', 'SyEditor', 'SyQuery']

    for (let i = 0; i < names.length; i++) {
      await clearData(names[i], model)
    }

    res.success()
  } catch (e) {
    console.log(e)
    res.error(e)
  }
})

Parse.Cloud.define('getSchemaNames', function (req, res) {
  const url = `${serverURL}/schemas`

  const options = {
    url: url,
    headers: {
      'X-Parse-Application-Id': appId,
      'X-Parse-Master-Key': masterKey,
      'Content-Type': 'application/json'
    }
  }

  Parse.Cloud.httpRequest(options).then(function (response) {
    if (response.status === 200) {
      const info = JSON.parse(response.body.toString())

      res.success(info.results.map(item => item.className))
    }
  }).catch(function (e) {
    console.log(e)
    res.error(e)
  })
})

/**
 * 根据schema，生成默认配置
 */
Parse.Cloud.define('genSchema', async (req, res) => {
  console.log('params', req.params)

  const {model} = req.params
  if (!model) {
    return
  }
  console.log(`gen schema ${model}`)

  const url = `${serverURL}/schemas${model ? '/' + model : ''}`
  console.log('url>>', url)

  const options = {
    url: url,
    headers: {
      'X-Parse-Application-Id': appId,
      'X-Parse-Master-Key': masterKey,
      'Content-Type': 'application/json'
    }
  }
  console.log('options>>>>', options)
  const schemas = []
  try {
    const response = await Parse.Cloud.httpRequest(options)
    if (response.status === 200) {
      const info = JSON.parse(response.body.toString())

      if (info.results) {
        schemas.push(...info.results)
      } else {
        schemas.push(info)
      }
    }

    const checkPromises = schemas.map(item => {
      return {
        isExist: checkIsSchemaExist(item.className),
        schema: item
      }
    })

    for (let i = 0, len = checkPromises.length; i < len; i++) {
      const item = checkPromises[i]
      const isExist = await item.isExist // 如果schema还没有生成过配置，则生成
      if (!isExist) {
        genSchema(item.schema)
      }
    }

    res.success('ok')
  } catch (e) {
    console.log(e)
    res.error(e)
  }
})

/**
 *
 * @param {string} className  检测schema是否已经生成过
 * @return {boolean}
 */
const checkIsSchemaExist = async (className) => {
  return (await new Parse.Query('SyResource').equalTo('name', className).count()) > 0
}

const TOOLBARS = [
  {
    'action': 'query',
    'type': 'global',
    'label': '查询'
  },
  {
    'action': 'add',
    'type': 'global',
    'label': '新增'
  },
  {
    'action': 'edit',
    'label': '修改'
  },
  {
    'action': 'delete',
    'label': '删除',
    'type': 'row,batch'
  },
]

const genSchema = (item) => {
  const list = []

  if (!item.className.startsWith('_')) {
    const fields = Object.keys(item.fields)
    const rfs = []  // SyResource
    const gfs = []  // SyGrid
    const efs = []  // SyEditor
    const qfs = [] // SyQuery.query
    const ofs = [] // SyOrder.order

    fields.forEach((fname) => {
      if (!names.includes(fname)) {
        const f = {}
        f.prop = fname
        f.label = getLabel(fname)
        const t = item.fields[fname]
        f.type = t.type
        if (t.type === 'Pointer') {
          f.targetClass = t.targetClass
        }
        rfs.push(f)

        if (t.type !== 'Pointer' && t.type !== 'Array' && t.type !== 'Object' && t.type !== 'File' && t.type !== 'Relation') {
          const gf = {}
          const o = {}
          gf.prop = fname
          o.prop = fname

          if (fname === 'updatedAt') {
            o.sort = 'desc'
          }

          if (t.type === 'Date') {
            gf.width = 145
            gf.formatter = 'date'
          } else if (t.type === 'Number') {
            gf.width = 80
          } else if (t.type === 'Boolean') {
            gf.width = 80
            gf.formatter = 'boolean'
          }
          gfs.push(gf)
          qfs.push({prop: fname})
          ofs.push(o)
        }

        efs.push({prop: fname})
      }
    })

    const toolbar = []
    // ['delete'].

    const r = new Parse.Object('SyResource')
    r.set('name', item.className)
    r.set('title', item.className)
    r.set('props', {props: rfs})

    const g = new Parse.Object('SyGrid')
    g.set('name', item.className)
    g.set('props', {columns: gfs, toolbars: TOOLBARS})

    const e = new Parse.Object('SyEditor')
    e.set('name', item.className)
    e.set('props', {props: efs})

    const q = new Parse.Object('SyQuery')
    q.set('name', item.className)
    q.set('props', {query: qfs, order: ofs})

    list.push(r)
    list.push(g)
    list.push(e)
    list.push(q)

  }
  Parse.Object.saveAll(list).then(function () {
  }).catch(console.log)
}

function getLabel (fname) {
  const map = {
    updatedAt: '更新时间',
    createdAt: '创建时间',
    name: '名称',
    seq: '顺序',
    status: '状态',
    title: '标题',
    description: '描述',
    url: '链接',
    picurl: '图片链接',
    prop: '属性',
    width: '宽度',
    height: '高度',
    nickname: '昵称',
    sex: '性别',
    isDelete: '是否删除',
    code: '代码',
    mobile: '手机号码',
    tel: '联系电话',
    contact: '联系人',
    babyName: '宝宝名',
    introduce: '介绍',
    content: '内容',
    price: '价格',
    payTime: '支付时间'
  }

  return map[fname] || fname
}
